<?php 
/*
 * 类taobaoApi争对淘宝api与实际业务操作的类
 * 引用类topClient
 * @time:2012-2-16
 * @author:Jack Hiron
 * @version:1.0
 * 
 sample示例
$taobao = new taobaoApi('tmall');

$order = $taobao->getOneOrder('143487116164579',$tradeAllFld);

$order = $taobao->getAllOrders(null,array('status'=>'WAIT_BUYER_PAY'));

$taobao->confirmOrder('143904531094188','EMS','107531767514');
正式环境
$taobao->confirmOrder('143487116164579','SF','107531767514');
$taobao->confirmSend('143487116164579','107531767514');
print_r($order);
*/


class taobaoApi{
	
	/*topClient对象，用于处于淘宝请求的核心对象*/
	protected static $client;
	
	/*淘宝提供会话sessionKey,请见config.php账号信息*/
	protected $session;
	
	/*是否显示错误信息*/
	private $showError = SHOW_ERR;
	
	/*是否为沙箱调试模式*/
	private $debug = API_DEBUG;
	
	
	/*
	 * 构告函数
	 * @param  string $accType 指定账号的类型
	 */
	public function __construct($accType){
	
		if(!function_exists('curl_init')){
			$this->error('系统不支持curl库,请修改php.ini');
			return false;
		}
		
		if(!class_exists('TopClient')){		
			$this->error('找不到淘宝接口类TopClient,请先加载');
			return false;			
		}
		
		
		if(self::$client==null){
			self::$client = new TopClient();
		}	
			
		if($this->debug){
			global $debugAccount;
			if( ($account = $debugAccount[$accType])== null ){
				$this->error('加载的调试账号不存在!');
				return false;				
			}
			self::$client->gatewayUrl = DEBUG_URL;
			
		}else{
			global $appAccount;
			if( ($account = $appAccount[$accType])== null ){
				$this->error('加载的账号不存在!');
				return false;				
			}	
			self::$client->gatewayUrl = TMALL_URL;
		}
		
		self::$client->appkey    = $account['appid'];
		self::$client->secretKey = $account['secret'];
		$this->session = $account['session'];
		
	}
	
	/*
	 * 获取一个订单
	 * @param string $tid订单号，不能用数值型，否则就会请求错误
	 * @parma array $flds 要获取的信息项.格式array('fld1','fld2'...)
	 * 请参考淘宝字段说明
	 * @return array 订单信息
	 */
	public function getOneOrder($tid,$flds=null){
		
		if(!class_exists('TradeFullinfoGetRequest')){
			$this->error('类TradeFullinfoGetRequest不存在!');
			return false;
		}
		
		$req = new TradeFullinfoGetRequest();
		if($flds!=null && is_array($flds)){
			$req->setFields(implode(',',$flds));
		}else{
			global $tradeFld;
			if($tradeFld==null || !is_array($tradeFld)){
				$this->error('taobaoApi->getOneOrder缺少参数$flds');
				return false;
			}
			$req->setFields(implode(',',$tradeFld));
		}

		$req->setTid($tid);		
		$resp = self::$client->execute($req,$this->session);
		if($this->isError($resp)){
		 	$this->error('taobaoApi->getOneOrder:'.$resp->code.' '.$resp->msg);
		 	return false;
		}else{
			if($resp!=null){
				return $resp->trade;
			}else{
				return null;
			}
		}
	}
	

	/*
	 * 获取最近30天的订单
	 * @parma array $flds 要获取的信息项.格式array('fld1','fld2'...)
	 * 请参考淘宝字段说明
	 * 
	 * @param array $cases 查询条件
	 * array('start'=>'开始时间','end'=>'结束时间',
	 * 'status'=>'订单状态','buyer'=>'买家妮称',
	 * 'type'=>'交易类型','ext_type'=>'订单类型','rate_status'=>'评价状态',
	 * 'tag'=>'商家自订议标签','page'=>'第几页','pagesize'=>'分页大小','nexpage'=>'是否下一页分页模式')
	 * 详情见分页说明字段表
	 * 
	 * @return array 订单信息
	 */	
	public function getAllOrders($flds=null,$cases=null){
	
		if(!class_exists('TradesSoldGetRequest')){
			$this->error('类TradesSoldGetRequest不存在!');
			return false;
		}
		
		$req = new TradesSoldGetRequest();
		if($flds!=null && is_array($flds)){
			$req->setFields(implode(',',$flds));
		}else{
			global $tradeFld;
			if($tradeFld==null || !is_array($tradeFld)){
				$this->error('taobaoApi->getAllOrders缺少参数$flds');
				return false;
			}
			$req->setFields(implode(',',$tradeFld));
		}

		/*增加条件查询*/
		if($cases!=null && is_array($cases)){
			
			if(isset($cases['status'])){
				$req->setStatus($cases['status']);
			}
			
			if(isset($cases['start'])){
				$req->setStartCreated( date('Y-m-d H:i:s',strtotime($cases['start'])) );	
			}
			
			if(isset($cases['end'])){
				$req->setEndCreated( date('Y-m-d H:i:s',strtotime($cases['end'])) );	
			}
			
			if(isset($cases['buyer'])){
				$req->setBuyerNick($cases['buyer']);
			}
			
			if(isset($cases['type'])){
				$req->setType($cases['type']);	
			}
			
			if(isset($cases['tag'])){
				$req->setTag($cases['tag']);	
			}
			
			if(isset($cases['rate_status'])){
				$req->setRateStatus($cases['rate_status']);
			}
			
			if(isset($cases['page'])){
				$req->setPageNo[$cases['page']];
			}
			
			if(isset($cases['pagesize'])){
				$req->setPageSize[$cases['pagesize']];
			}			
		}
		
		$resp = self::$client->execute($req,$this->session);
		if($this->isError($resp)){
		 	$this->error('taobaoApi->getAllOrders:'.$resp->code.' '.$resp->msg);
		 	return false;
		}else{
			if($resp!=null){
				return $resp->trades;
			}else{
				return null;
			}
		}			
	}
	
	/*
	 *确定发货操作
	 *@param string $tid 订单号
	 *@param string $sid 快递单号
	 *@reutn 成功true,失败false;
	 */
	public function confirmSend($tid,$sid){
	
		if(!class_exists('LogisticsOnlineConfirmRequest')){
			$this->error('类 LogisticsOnlineConfirmRequest不存在!');
			return false;
		}
		
		$order = $this->getOneOrder($tid,array('status'));
		if(!$order || $order->status!='WAIT_SELLER_SEND_GOODS'){
			$this->error('不存在的订单，或买家没有付款或已经发货!');
			return false;
		}

		$req = new LogisticsOnlineConfirmRequest();
		$req->setTid($tid);
		$req->setOutSid($sid);
		
		$resp = self::$client->execute($req,$this->session);
		if($this->isError($resp)){
		 	$this->error('taobaoApi->confirmSend:'.$resp->code.' '.$resp->sub_code.' '.$resp->msg.' '.$resp->sub_msg);
		 	return false;
		}else{
			return $resp;
		}			
		
	}
	
	/*
	 * 卖家确认发货信息
	 * @param string $tid 订单号
	 * @param string $compnay 快弟公司编码
	 * @param string $sid快递单kgn
	 */
	public function confirmOrder($tid,$company,$sid=''){
		if(!class_exists('LogisticsOfflineSendRequest')){
			$this->error('类 LogisticsOfflineSendRequest不存在!');
			return false;
		}
		
		$order = $this->getOneOrder($tid,array('status'));
		if(!$order || $order->status!='WAIT_SELLER_SEND_GOODS'){
			$this->error('不存在的订单，或买家没有付款或已经发货!');
			return false;
		}
		
		$req = new LogisticsOfflineSendRequest();
		$req->setTid($tid);
		$req->setCompanyCode($company);
				
		if($sid!=''){
			$req->setOutSid($sid);		
		}
		
		$resp = self::$client->execute($req,$this->session);
		if($this->isError($resp)){
		 	$this->error('taobaoApi->confirmOrder:'.$resp->code.' '.$resp->sub_code.' '.$resp->msg.' '.$resp->sub_msg);
		 	return false;
		}else{
			return $resp;
		}			
	
	}
	
	
	/*
	 * 获取商品信息
	 * @param string $pid 商品iid
	 * @param array $flds 获取的字段
	 * @return xml
	 */
	public function getProduct($pid,$flds=null){
		
		if(!class_exists('ItemGetRequest')){
			$this->error('类ItemGetRequest不存在!');
			return false;
		}
		
		$req = new ItemGetRequest();
		
		if($flds!=null && is_array($flds)){
			$req->setFields(implode(',',$flds));
		}else{
			global $prodFlds;
			if($prodFlds==null || !is_array($prodFlds)){
				$this->error('taobaoApi->getProduct缺少参数$flds');
				return false;
			}
			$req->setFields(implode(',',$prodFlds));
		}
		
		$req->setNumIid($pid);		
		$resp = self::$client->execute($req,$this->session);
		if($this->isError($resp)){
		 	$this->error('taobaoApi->getProduct:'.$resp->code.' '.$resp->sub_code.' '.$resp->msg.' '.$resp->sub_msg);
		 	return false;
		}else{
			return $resp->item;
		}			
		
	}
	
	/*
	 * 获取相关物流公司
	 */
	protected function getShipCompany(){
	
		if(!class_exists('LogisticsCompaniesGetRequest')){
			$this->error('类 LogisticsCompaniesGetRequest不存在!');
			return false;
		}

		self::$client->format = 'json';
		$req = new LogisticsCompaniesGetRequest();
		$req->setFields("id,code,name");
		$resp = self::$client->execute($req,$this->session);
		
		if($this->isError($resp)){
		 	$this->error('taobaoApi->confirmOrder:'.$resp->code.' '.$resp->sub_code.' '.$resp->msg.' '.$resp->sub_msg);
		 	return false;
		}else{
			if($resp!=null){
				return $resp->logistics_companies->logistics_company;
			}
		}			
		
	
	}
	
	
	/*
	 * 判断是否为已完成订单
	 * @param string $tid 淘宝订单号
	 * @return 是true,false不是
	 */
	public function isFinishedOrder($tid){
		
		$order = $this->getOneOrder($tid,array('status'));
		if(!$order || $order->status!='TRADE_FINISHED'){
			return false;
		}else{
			return true;		
		}
	
	}
	
	
	/*
	 * 判断返回数据是否有错误信息
	 * @param array $resp 返回数据
	 * @return true/false true是,false不是
	 */
	protected function isError($resp){
	
		if(isset($resp->code) && isset($resp->msg)){
			return true;
		}else{
			return false;
		}
	}
	

	
	/*
	 * 错误报告
	 * @param string $exception 错误信息
	 */
	protected function error($exception){
	
		if($this->showError == false){
			return;
		}
		
		if(class_exists('error') && is_object($GLOBALS['error'])){			
			$GLOBALS['error']->showErrorStr($exception,'javascript:',false);
		}else{
			throw new Exception($exception);
		}	
	}
}


?>